﻿module Sustainalytics.EsgRatings {

    import Common = Sustainalytics.Common;
    import Company = Sustainalytics.Company;
    import Research = Sustainalytics.Research;
    import LRTM = Sustainalytics.LRTM;

    export class EsgController extends Research.ResearchPageController {

        // currently active view
        public viewName: string;

        // whether current view is still loading
        public isInitLoading: boolean;

        // employee in charge with respective industry
        public industryLeadPersonnel: EsgIndustryLeadPersonnelDto;


        public hasEsgUniverse: boolean = true;
        public hasControversiesUniverse: boolean = true;


        public hasEsgResearch: boolean;
        public hasControversiesResearch: boolean;
  

        constructor(
            protected $scope: Company.ICompanyBasedScope,
            protected $q: ng.IQService,
            protected $timeout: ng.ITimeoutService,
            protected $location: ng.ILocationService,
            protected $routeParams: ng.route.IRouteParamsService,
            protected CompanyService: Company.ICompanyService,
            protected EsgIndustryLeadPersonnelService: IEsgIndustryLeadPersonnelService,
            protected NumberUtilityService: Common.NumberUtilityService,
            protected MostActiveReportService: MostActiveReports.MostActiveReportService,
            protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private $filter: ng.IFilterService,
            private $rootScope) {

            super($scope, $q, $location, $routeParams, CompanyService);

            var ctx = this;

            $scope['esg'] = ctx;

            ctx.init();
        }

        // init logic
        private init(): ng.IPromise<any> {
            var ctx = this;

            ctx.isInitLoading = true;

            var def = ctx.$q.defer();

            var initPromise = super.initPage();

            // set EsgSummary view as the default view
            initPromise.then(
                // success
                function () {

                    ctx.hasEsgResearch = ctx.company.hasEsgResearch;
                    ctx.hasControversiesResearch = ctx.company.hasControversyResearch;

                    //var companyEsgUniverse_Promise = ctx.CompanyService.getById(ctx.company.id, Common.AccountFeature.EsgRatingsOnlineReport);
                    //var companyControversies_Promise = ctx.CompanyService.getById(ctx.company.id, Common.AccountFeature.Controversies);

                    var companyEsgUniverse_Promise = ctx.getCompanyInEsgResearchUniverse(ctx.company.id);
                    var companyControversies_Promise = ctx.getCompanyInControversiesUniverse(ctx.company.id);

                    ctx.$q.all([companyEsgUniverse_Promise, companyControversies_Promise]).then(
                        // success
                        function () {

                            console.log("hasEsgUniverse: " + ctx.hasEsgUniverse);
                            console.log("hasControversiesUniverse: " + ctx.hasControversiesUniverse);

                            ctx.$timeout(function () {
                                ctx.$scope.$apply(function () {

                                    ctx.changeView(EsgViewNames.EsgSummary);
                                    
                                    // get industry lead personnel
                                    ctx.getindustryLeadPersonnel().then(
                                        // success
                                        function () { def.resolve(); },
                                        // error
                                        function () { def.reject(); });
                                });
                            });

                            def.resolve();
                        },
                        // error
                        function (reason) {
                            def.reject(reason);
                        });

                },
                // error
                function (reason) {
                 
                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Esg Controller -> Error initializing' });
                
                    def.reject(reason);
                });

            var promise = def.promise;

            promise['finally'](function () {
                ctx.isInitLoading = false;
            });

            return promise;
        }


        //init Esg Research is in universe
        private getCompanyInEsgResearchUniverse(companyId): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.CompanyService.getById(companyId, Common.AccountFeature.EsgRatingsOnlineReport)
                .then(
                function (company) {
                    ctx.hasEsgUniverse = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    //if (reason.status !== 404 && reason.status !== 401) { }
                    def.reject(reason);
                });

            return def.promise;
        }

        //init Controversies is in universe
        private getCompanyInControversiesUniverse(companyId): ng.IPromise<Company.CorporateDataExtendedDto> {
            var ctx = this;
            var def = ctx.$q.defer();

            ctx.CompanyService.getById(companyId, Common.AccountFeature.Controversies)
                .then(
                function (company) {
                    ctx.hasControversiesUniverse = company.data.isEnabled;
                    def.resolve(company);
                },
                function (reason) {
                    //if (reason.status !== 404 && reason.status !== 401) { }
                    def.reject(reason);
                });

            return def.promise;
        }


        // init - get industry lead personnel
        private getindustryLeadPersonnel(): ng.IPromise<EsgIndustryLeadPersonnelDto> {
            var ctx = this;

            var promise = ctx.EsgIndustryLeadPersonnelService.get(ctx.company.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.industryLeadPersonnel = res;
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: Esg Controler -> Error loading Industry Lead' });
                });

            return promise;
        }

        public addCompanyReportToMostActiveReports(){
            var ctx = this;
            var now = new Date();
           
            var reportName = ctx.company.companyNameUrlFriendly + "_ESGRatingsReport_" + ctx.$filter('date')(now, "ddMMyyyy");
            ctx.MostActiveReportService.addReport(ctx.company.id);

            ctx.LongRunningTaskManagerService.runTask(reportName ,
                JSON.stringify(ctx.company.id),
                LRTM.LongRunningTaskTypeEnum.CompanyReportPDF, true, null);

            ga('create', 'UA-4379897-6', {
                'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Report', 'eventAction': 'ESG', 'eventLabel': ctx.company.id
            });
        }

        public addControversyReportToMostActiveReports() {
            var ctx = this;
            var now = new Date();

            var reportName = ctx.company.companyNameUrlFriendly + "_ControversyReportPDF_" + ctx.$filter('date')(now, "ddMMyyyy");
            ctx.LongRunningTaskManagerService.runTask(reportName,
                JSON.stringify(ctx.company.id),
                LRTM.LongRunningTaskTypeEnum.ControversyReportPDF, true, null);

            ga('create', 'UA-4379897-6', {
                'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Report', 'eventAction': 'Controversy', 'eventLabel': ctx.company.id
            });
        }

        // change currently active view
        public changeView(viewName: string): void {
            var ctx = this;
            ctx.viewName = viewName;

            ga('create', 'UA-4379897-6', {
                'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
            });

            ga('globalAccess.send', {
                'hitType': 'event', 'eventCategory': 'Onscreen-Report', 'eventAction': 'ESG-Tab', 'eventLabel': viewName
            });

        }

        public getViewNames(): EsgViewNames {
            return EsgViewNames;
        }


        public GetEsgPdfDownloadEnabled(): boolean {
            var ctx = this;
            var result = true;

            if (!ctx.hasEsgResearch || !ctx.hasEsgUniverse  ) {
                result = false;
            }

            return result;
        }

        public GetControversiesPdfDownloadEnabled(): boolean {
            var ctx = this;
            var result = true;

            if (!ctx.hasControversiesResearch || !ctx.hasEsgUniverse) {
                result = false;
            }

            return result;
        }

    }


    angular.module(esgRatingsModuleName).controller('EsgController', EsgController);
} 